#pragma once
#include <string>
#include <cstring>
#include <cerrno>
#include <memory>
#include <functional>
#include <strings.h>
#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "Dictionary.hpp"
const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1";
const static uint16_t gdefaultport = 8080;

using func_t = std::function<std::string(const std::string &)>;
using namespace LogMoudule;
class UdpServer
{
public:
    UdpServer(func_t func,uint16_t port = gdefaultport)
        : _inetaddr(port),
          _isrunning(false),
          _sockfd(gsockfd),
          _func(func)
    {
    }
    void InitServer()
    {
        // 创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            LOG(LogLevel::FATAL) << "socket：" << strerror(errno);
            Die(1);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is : " << _sockfd;

        // 2.填充网络信息
        InetAddr local(_inetaddr.GetPort());
        // 2.1 bind
        int n = ::bind(_sockfd, local.GetNetAddrPtr(), local.GetNetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(2);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len);
            if (n > 0)
            {
                // 1.消息内容 && 2.谁发给我的
                // uint16_t clientport = ::ntohs(peer.sin_port);
                // std::string clientip;
                // clientip = ::inet_ntoa(peer.sin_addr);
                InetAddr cli(peer);
                std::string clientinfo = cli.GetIp() + ":" + std::to_string(cli.GetPort());
                inbuffer[n] = 0;

                LOG(LogLevel::DEBUG) << clientinfo << " client say@ " << inbuffer;
                std::string echo_string =_func(inbuffer);
                ::sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, cli.GetNetAddrPtr(), cli.GetNetAddrLen());
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    InetAddr _inetaddr;
    int _sockfd;
    // uint16_t _port; // 服务器未来的端口号
    // std::string _ip; // 服务器所对应的ip
    bool _isrunning; // 服务器运行状态

    // 业务
    func_t _func;
};